package com.yummy.controller;


import com.github.pagehelper.PageInfo;
import com.yummy.common.BaseResponse;

import com.yummy.common.IDTools;
import com.yummy.common.TokenUtils;
import com.yummy.dto.QueryOrderVo;
import com.yummy.entity.*;
import com.yummy.service.AddressService;
import com.yummy.service.OrderDetailService;
import com.yummy.service.OrdersService;
import com.yummy.service.ShoppingCartService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;


@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private OrdersService orderService;

    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private IDTools idTools;
    @Autowired
    private AddressService addressService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;


    Logger logger = LoggerFactory.getLogger(OrderController.class);


    @PutMapping("/modifyStatus")
    public BaseResponse modify(@RequestBody Orders orders){


        int result = orderService.modifyOrderById(orders);
        if(result==1){
            return BaseResponse.success();

        }else{
            return BaseResponse.fail();
        }

    }

    /*取消订单*/
    @PostMapping("/modifyForDelete")
    public BaseResponse modifyForDelete(@RequestParam String[] ids){
        for(String id :ids){
            System.out.println(id);
        }
        int result = orderService.modifyOrderForDeleteByPrimaryKey(ids);
        if(result>0){
            return BaseResponse.success();
        }else{
            return BaseResponse.fail();
        }
    }

    /*表单修改*/
    @PostMapping("/modifyOrder")
    public BaseResponse modifyOrder(@RequestBody Orders orders,HttpServletRequest request){
        System.out.println(orders);

        Integer currentStore = tokenUtils.getCurrentStore(request);
        logger.info(orders.toString());

        int result = orderService.modifyOrder(orders);
        if(result==1){
            return BaseResponse.success().message("修改成功");

        }else{
            return BaseResponse.fail().message("修改失败");
        }

    }


    /*查询指定店铺所包含的订单*/
     @PostMapping("/selectAllOfAccount")
     public BaseResponse selectAllOrder(@RequestBody QueryOrderVo queryOrderVo, HttpServletRequest request){
        System.out.println("页面来的"+queryOrderVo);
         Integer currentStore = tokenUtils.getCurrentStore(request);
        PageInfo<Orders> pageInfo = orderService.selectAllOrderByCondition(currentStore,queryOrderVo);
        return BaseResponse.success().data("orderList",pageInfo);
     }

     /*查询指定店铺 且进行多条件查询所含订单*/
   /* @PostMapping("/selectAllOfAccountByCondition")
    public BaseResponse selectAllOrderByCondition(@RequestBody QueryOrderVo queryOrderVo, HttpServletRequest request){
        Integer currentStore = tokenUtils.getCurrentStore(request);
        System.out.println("页面来有条件的"+queryOrderVo);
        PageInfo<Orders> pageInfo = orderService.selectAllOrderByCondition(currentStore,queryOrderVo);
        return BaseResponse.success().data("orderList",pageInfo);
    }*/





    /*查询个人用户所含的订单 */
     @PostMapping("/selectOrderOfUser")
    public BaseResponse selectOrderByUserId(HttpServletRequest request){

         User currentUser = tokenUtils.getCurrentUser(request);
         logger.info("根据token获取到的用户信息"+currentUser.toString());
         List<Orders> pageInfo = orderService.selectAllOrderOfUser(currentUser.getId());
         System.out.println(pageInfo);
         logger.info(pageInfo.toString());
         if(pageInfo==null){
             return BaseResponse.fail().message("未查询到结果");
         }else{
             return BaseResponse.success().data("orderList",pageInfo);}
     }

     /*未支付的*/
    @PostMapping("/selectOrderOfUser2")
    public BaseResponse selectOrderByUserId2(HttpServletRequest request){

        User currentUser = tokenUtils.getCurrentUser(request);
        logger.info("根据token获取到的用户信息"+currentUser.toString());
        List<Orders> pageInfo = orderService.selectAllOrderOfUser2(currentUser.getId());
        System.out.println(pageInfo);
        logger.info(pageInfo.toString());
        if(pageInfo==null){
            return BaseResponse.fail().message("未查询到结果");
        }else{
            return BaseResponse.success().data("orderList",pageInfo);}
    }


    /*待收货的*/
    @PostMapping("/selectOrderOfUser3")
    public BaseResponse selectOrderByUserId3(HttpServletRequest request){

        User currentUser = tokenUtils.getCurrentUser(request);
        logger.info("根据token获取到的用户信息"+currentUser.toString());
        List<Orders> pageInfo = orderService.selectAllOrderOfUser3(currentUser.getId());
        System.out.println(pageInfo);
        logger.info(pageInfo.toString());
        if(pageInfo==null){
            return BaseResponse.fail().message("未查询到结果");
        }else{
            return BaseResponse.success().data("orderList",pageInfo);}
    }


    /*待评价的*/
    @PostMapping("/selectOrderOfUser4")
    public BaseResponse selectOrderByUserId4(HttpServletRequest request){

        User currentUser = tokenUtils.getCurrentUser(request);
        logger.info("根据token获取到的用户信息"+currentUser.toString());
        List<Orders> pageInfo = orderService.selectAllOrderOfUser4(currentUser.getId());
        System.out.println(pageInfo);
        logger.info(pageInfo.toString());
        if(pageInfo==null){
            return BaseResponse.fail().message("未查询到结果");
        }else{
            return BaseResponse.success().data("orderList",pageInfo);}
    }

    @PostMapping("/selectOrderAccountOfUser")

    public BaseResponse selectOrderAccountByUserId(HttpServletRequest request){

        User currentUser = tokenUtils.getCurrentUser(request);
        logger.info("根据token获取到的用户信息"+currentUser.toString());
        int pay = orderService.selectOrderAccountOfUser(currentUser.getId());
        int pay2 = orderService.selectOrderAccountOfUser2(currentUser.getId());
        int pay3 = orderService.selectOrderAccountOfUser3(currentUser.getId());
        System.out.println(pay);
        int[] array =new int[3];
        array[0]=pay;
        array[1]=pay2;
        array[2]=pay3;
        return BaseResponse.success().data("orderArray",array).data("user",currentUser);



    }

     /*根据订编号查找订单详细内容*/
    @PostMapping("/selectOrderDetailByOrderId/{orderId}")
    public BaseResponse selectOrderDetailByOrderId(@PathVariable("orderId") Integer orderId){
        List<OrderDetail> detailsList = orderService.selectOrderDetailByOrderId(orderId);
        return BaseResponse.success().data("detailsList",detailsList);
    }

    @PostMapping("/submit")
    @Transactional
    public BaseResponse submit(@RequestBody List<ShoppingCart> cartList, HttpServletRequest request){
        System.out.println(cartList);

        //获取user
        User currentUser = tokenUtils.getCurrentUser(request);
        //生成orderId
        String number = IDTools.getId();
        //查询到storeId
        int storeId = cartList.get(0).getStoreId();
        System.out.println(number);
        //获取默认address
        AddressBook addressBook = addressService.queryDefault(currentUser.getId());
        //总价格
        double total = 0;

        //批处理请求cart
        for (ShoppingCart shoppingCart : cartList) {
            total=shoppingCart.getNumber()*shoppingCart.getAmount().longValue();
        }

        //组装orders
        Orders orders = new Orders();
        orders.setNumber(number);
        orders.setStatus(1);
        orders.setAccountId(storeId);
        orders.setUserId(currentUser.getId().longValue());
        orders.setAddressBookId(addressBook.getId());
        orders.setPayMethod(1);
        orders.setAmount(BigDecimal.valueOf(total));
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()
                +addressBook.getDistrictName()+addressBook.getDetail());
        orders.setUserName(currentUser.getName());
        orders.setConsignee(addressBook.getConsignee());


        //orders持久化并且获取id
        int result = orderService.addOrder(orders);
        System.out.println("orders:"+orders);
        Long orderId = orders.getId();

        //同步订单详情
        boolean detailRs = orderDetailService.addBatch(cartList, orderId);

        //清空购物车
        boolean cartRs = shoppingCartService.clearCarts(cartList);
        //返回orderNumber
        return BaseResponse.success().data("orderId",number);
    }



}
